#!/usr/bin/env python3
import re
from subprocess import Popen
import time

#安全日志
LogFile = "var/log/secure"
#黑名单
hostDeny = "/etc/hosts.deny"
#阈值
tv = 5

#读取黑名单的ip，将ip写入字典
def dic_ip():
    dict_ip = {}
    list = open(hostDeny).readlines()#读取每一行作为一个列表
    for ip in list:
        group = re.search('\d+\.\d+\.\d+\.\d+',ip)
        if group:
            dict_ip[group[1]]='1'#ip为字典的键，'1'为字典的值。
    return dict_ip

#监控方法
def monitorlog(Logfile):
    #统计阈值次数
    tv_num = {}
    #获取黑名单ip字典
    dict_ip = dic_ip()
    #读取十条安全日志
    rd_Log = subprocess.Popen("tail -f"+LogFile,stdout = subprocess.PIPE,stderr=subprocess.PIPE,shell = True)
    while True:
        time.sleep(0.1)
        line = rd_Log.stdout.readlines()
        if line:
            group = re.search('Invalid user \w+ from (\d+\.\d+\.\d+\.\d+\)',str(line))
            #不存在的用户直接封ip
            if group and not dict_ip:
                subprocess.getoutput('echo\'sshd:{}>>{}'.format(group[1]),hostDeny)
                dict_ip[group[1]] = '1'
                time_str = time.strftime('%Y-%m-%d %H:%M:%S'.time.localtime(time.time()))
                print('{} ---add ip:{} to hosts.deny for invalid user'.format(time_str,group[1]))
                continue
            #用户名合法，密码错误超过阈值
            group = re.search('Failed password \w+ from (\d+\.\d+\.\d+\.\d+)',str(line))
            if group:
                ip =group[1]
                if not tv_num.get(ip):
                    tv_num[ip] = 1
                else:
                    tv_num[ip] = tv_num[ip]+1
                #如果错误次数大于阈值，且字典中不存在键为该ip的键值对，封禁ip放入黑名单
                if tv_num[ip] > tv and not dict_ip.get[ip]:
                    del tv_num[ip]
                    subprocess.getoutput('echo \'sshd:{}>>{}'.format(ip,hostDeny))
                    dict_ip[ip] = '1'
                    time_str = time.strftime('%Y-%m-%d %H:%M:%S'.time.localtime(time.time()))
                    print('{} ---add ip:{} to hosts.deny for invalid user'.format(time_str,group[1]))

if __name__ =='__main__':
    monitorlog(LogFile)
#密码暴力破解自动阻断
#1、打开安全日志
#2、对安全日志进行实时监控
#3、解析日志每一行内容找出正在爆破的ip
#4、设置阈值，超过阈值封禁，将ip放进黑名单
